package cn.zero.letaomallspringboot.controller;

import cn.hutool.core.util.StrUtil;
import cn.zero.letaomallspringboot.common.JwtUtil;
import cn.zero.letaomallspringboot.common.Result;
import cn.zero.letaomallspringboot.entity.DTO.AdminLoginDTO;
import cn.zero.letaomallspringboot.entity.Admin;
import cn.zero.letaomallspringboot.service.IAdminService;
import cn.zero.letaomallspringboot.service.impl.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import cn.zero.letaomallspringboot.Constant.ResultCode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("/admin")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    private final IAdminService adminService;

    public AdminController(IAdminService userService) {
        this.adminService = userService;
    }

    @PostMapping("/login")
    public Result<Object> login(@RequestBody AdminLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        boolean rememberMe = userLoginDTO.isRememberMe();
        log.info("管理员登录: username: {}, password: {}", username, password);
        Admin user = adminService.login(username, password, rememberMe);

        // 生成JWT token
        String token = JwtUtil.createToken(user.getUid().toString(), user.getUsername());

        // 返回token和user
        Map<String, Object> response = new HashMap<>();
        response.put("token", token);
        response.put("user", user);

        return Result.success(response, "欢迎你:" + username);
//        return Result.success(user, "欢迎你:" + username);
    }

    @GetMapping("/all")
    public Result<List<Admin>> users(HttpServletRequest request) {
        log.info("管理员列表");
        List<Admin> users = adminService.user();
        return Result.success(users);
    }

    // 2. 根据ID查询单个管理员（编辑回显）
    @GetMapping("/{id}")
    public Result<Admin> getById(@PathVariable Integer id) {
        log.info("根据ID查询管理员，id: {}", id);
        Admin admin = adminService.getById(id);
        if (admin == null) {
            return Result.fail(ResultCode.ADMIN_NOT_FOUND);
        }
        return Result.success(admin);
    }

    // 3. 新增管理员
    @PostMapping("/add")
    public Result<String> add(@RequestBody @Valid Admin admin) {
        log.info("新增管理员，username: {}", admin.getUsername());
        boolean success = adminService.addAdmin(admin);
        if (!success) {
            return Result.fail(ResultCode.ADMIN_ADD_FAILED);
        }
        return Result.success("新增成功");
    }

    // 4. 根据ID编辑管理员
    @PutMapping("/update/{id}")
    public Result<String> update(@PathVariable Integer id, @RequestBody @Valid Admin admin) {
        log.info("编辑管理员，id: {}", id);
        admin.setUid(id);
        boolean success = adminService.updateAdmin(admin);
        if (!success) {
            return Result.fail(ResultCode.ADMIN_UPDATE_FAILED);
        }
        return Result.success("更新成功");
    }

    // 5. 根据ID删除管理员
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        log.info("删除管理员，id: {}", id);
        boolean success = adminService.deleteById(id);
        if (!success) {
            return Result.fail(ResultCode.ADMIN_DELETE_FAILED);
        }
        return Result.success("删除成功");
    }

    // 6. 多条件分页查询
    @GetMapping("/search")
    public Result<List<Admin>> search(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String role) {

        log.info("多条件查询管理员，username: {}, email: {}, role: {}", username, email, role);
        List<Admin> list = adminService.search(username, email, role);
        return Result.success(list);
    }

    @PutMapping("/changePassword/{id}")
    public Result<String> changePassword(@PathVariable Integer id, @RequestBody Map<String, String> map) {
        String password = map.get("password");
        if (StrUtil.isBlank(password)) {
            return Result.fail(ResultCode.PARAM_VALID_ERROR);
        }

        boolean success = adminService.changePassword(id, password);
        return success ? Result.success("修改密码成功") : Result.fail(ResultCode.ADMIN_NOT_FOUND);
    }
}
